﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BMUpload.Utility;


namespace BMUpload
{
    public partial class FrmUpload : Form
    {
        UploadBLL p ;

        public FrmUpload()
        {
            InitializeComponent();
            InitToolsBar();
            Inittabcontrol();
            FreshComboxHis();
            InitComDate();
        }

        private void InitToolsBar()
        {
            toolbar.Items.Clear();
            toolbar.Top = 0;
            toolbar.ImageList = imageList1;
            string strfunc = string.Empty;
            strfunc += "#Search*查询*查询需要上传的信息*search";
            strfunc += "#Send*上报*上报查询出来的信息*up";
            strfunc += "#Result*结果*查询上报结果*Rlt";
            strfunc += "#ToExcel*导出*导出到EXCEL*excel";
            strfunc += "#Exit*返回*推出当前窗口*home";


            string[] arr = strfunc.Split('#');
            for (int i = 1; i < arr.Length; i++)
            {
                string[] tbarr = arr[i].Split('*');
                ToolStripButton tb = new ToolStripButton();
                
                tb.Text = tbarr[1];
                tb.ToolTipText = tbarr[2];
                tb.ImageKey = tbarr[3];
                tb.TextAlign = ContentAlignment.BottomCenter;
                tb.TextImageRelation = TextImageRelation.ImageAboveText;
                tb.Click += new EventHandler(tb_Click);
                toolbar.Items.Add(tb);
            }


        }

        private void Inittabcontrol()
        {
            tabControl1.TabPages.Clear();

            string strfunc = string.Empty;
            strfunc += "#ltqyJhEntry*进货信息*查询需要上传的信息*1";
            strfunc += "#ltqyJhmx_XmEntry*进货箱码信息*查询需要上传的信息*1";
            strfunc += "#ltqyXsEntry*销售信息*查询需要上传的信息*1";
            strfunc += "#lsqyXsEntry*零售信息*查询需要上传的信息*1";
            strfunc += "#ltqyXsmx_XmEntry*销售箱码信息*查询需要上传的信息*1";
            strfunc += "#ltqyThEntry*进货退货信息*查询需要上传的信息*1";
            strfunc += "#ltqyThmxXm_XmEntry*退货箱码信息*查询需要上传的信息*1";
            strfunc += "#scqyCpjysmEntry*检验报告信息*查询需要上传的信息*1";
            
            
            string[] arr = strfunc.Split('#');
            for (int i = 1; i < arr.Length; i++)
            {
                string[] tbarr = arr[i].Split('*');
                
                TabPage tp=new TabPage ();
                tp.Name =tbarr[0];
                tp.Text = tbarr[1];
                tp.ToolTipText = tbarr[2];
                tp.ImageKey = tbarr[3];
                //tp.Font.Size = 12;
                //tp.Font.Bold = true;
                #region 添加网格
                DataGridView dg = new DataGridView();
                dg.Name ="GV" + tbarr[0];
                dg.Dock = DockStyle.Fill;
                dg.AllowUserToAddRows = false;
                if (Common.Right(tbarr[0], "_XmEntry".Length).Equals("_XmEntry"))
                { }
                else if (tbarr[0].Equals("scqyCpjysmEntry"))
                {}
                else
                {
                    dg.ReadOnly = true;
                }
                dg.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dg_DataBindingComplete);
                dg.RowPostPaint += new DataGridViewRowPostPaintEventHandler(dg_RowPostPaint);
                dg.CellContentClick += dg_CellContentClick;
                tp.Controls.Add(dg);
                #endregion
                tabControl1.TabPages.Add(tp);
            }
        }

        void dg_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                string sjlx = tabControl1.SelectedTab.Name;
                if (sjlx.Equals("scqyCpjysmEntry"))
                {
                    DataGridView Mygrid;
                    Mygrid = GetShowgrid();
                    if (Mygrid.Columns[e.ColumnIndex].Name.Equals("browse"))
                    {
                        string path = FileHelper.OpenFile("所有(*.*)|*.*|PDF文件 (*.PDF)|*.PDF", "");
                        if (!string.IsNullOrEmpty(path))
                        { 
                            //Mygrid.Columns["FILE_CONTENT"].
                            //判断文件大小
                            if (FileHelper.FileLenth(path) > 10240)
                            {
                                MsgHelper.ShowInformationMsgBox("所选择的文件过大，不能超过10M");
                                return;
                            }
                            Mygrid.BeginEdit(false);
                            Mygrid.Rows[e.RowIndex].Cells["FILE_CONTENT"].Value = path;
                            Mygrid.EndEdit();
                            Mygrid.CurrentCell = null;
                            //DataTable dt = (DataTable)Mygrid.DataSource;
                            //dt.Rows[e.RowIndex]["FILE_CONTENT"] = path;
                            //dt.AcceptChanges();
                        }
                    }
                }
            }
        }

        private void InitComDate()
        {
            DateSelect.Items.Clear();
            DateSelect.Items.Add("时段选择");
            DateSelect.Items.Add("今天");
            DateSelect.Items.Add("昨天");
            DateSelect.Items.Add("上旬");
            DateSelect.Items.Add("中旬");
            DateSelect.Items.Add("下旬");
            DateSelect.Items.Add("本月");
            DateSelect.Items.Add("上月");
            DateSelect.Items.Add("本年");
            DateSelect.SelectedIndex = 0;
        }

        void dg_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //throw new NotImplementedException();
            DataGridView Mygrid=(DataGridView)sender;
            Rectangle rowHeaderBounds = new Rectangle
            (
                 2, e.RowBounds.Top,
                 Mygrid.RowHeadersWidth - 2, e.RowBounds.Height - 1
                 
            );

            using (Brush backbrush =
                new SolidBrush(SystemColors.Control))
            {
                e.Graphics.FillRectangle(backbrush, rowHeaderBounds);
            }

            if (e.RowIndex >= Mygrid.FirstDisplayedScrollingRowIndex)
            {
                using (SolidBrush b = new SolidBrush(Mygrid.RowHeadersDefaultCellStyle.ForeColor))
                {
                    int linen = 0;
                    linen = e.RowIndex + 1;
                    string line = linen.ToString();
                    e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
                    SolidBrush B = new SolidBrush(Color.Red);
                }
            }
        }

        void dg_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            SetGrifCap(sender);
            SetGridEnEdit(sender);
        }

        void tb_Click(object sender, EventArgs e)
        {
            try
            {
                if (((ToolStripButton)sender).Text.Equals("查询"))
                { SearchData(); }
                else if (((ToolStripButton)sender).Text.Equals("上报"))
                {
                    if (MsgHelper.ShowQuestionMsgBox("是否将" + tabControl1.SelectedTab.Text + "查询结果上传到省追溯平台") == DialogResult.Yes)
                    {
                        SendData();
                    }
                }
                else if (((ToolStripButton)sender).Text.Equals("返回"))
                {
                    this.Close();
                }
                else if (((ToolStripButton)sender).Text.Equals("导出"))
                {
                    ToExcel();
                }
                else if (((ToolStripButton)sender).Text.Equals("结果"))
                {
                    LookResult();
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgBox(ex.Message); 
            }
        }



        private void ToExcel()
        {
            string sjlx = tabControl1.SelectedTab.Text ;
            DataGridView Mygrid;

            Mygrid = GetShowgrid();
            ExcelHelper excel = new ExcelHelper();
            excel.ExportExcel(sjlx, Mygrid, Mygrid.Font.Name, 9); 
        }
        /// <summary>
        /// 查询数据
        /// </summary>
        private void SearchData()
        {
            try
            {
                if (p == null)
                {
                    p = new UploadBLL();
                }
            
                string sjlx = tabControl1.SelectedTab.Name; 
                UploadArgs e = new UploadArgs();
                e.BeginDate = dtBegin.Value.ToShortDateString();
                e.EndDate = dtEnd.Value.ToShortDateString();
                e.SearchHIS = radioButton2.Checked;
                e.DocumentID = comboUpHIS.Text;

                DataGridView Mygrid;

                Mygrid = GetShowgrid();
                DataSet ds = p.SearchData(sjlx, e);
                if (ds.Validate())
                {
                    Mygrid.Columns.Clear();
                    Mygrid.DataSource = ds.Tables[0];
                    if (sjlx.Equals("scqyCpjysmEntry"))
                    {
                        if (!Mygrid.Columns.Contains("browse"))
                        {
                            DataGridViewButtonColumn gigUrlColumn = new DataGridViewButtonColumn();
                            gigUrlColumn.HeaderText = "";
                            gigUrlColumn.Name = "browse";
                            gigUrlColumn.Text = "...";
                            gigUrlColumn.UseColumnTextForButtonValue = true;
                            gigUrlColumn.Width = 32;
                            Mygrid.Columns.Add(gigUrlColumn);
                        }
                        else
                        {
                            Mygrid.Columns["browse"].HeaderText = ""; 
                        }
                    }
                    
                }
                else
                {
                    MsgHelper.ShowInformationMsgBox("查不到任何数据！"); 
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgBox("查询出现错误:" + ex.Message); 
            }
        }
        /// <summary>
        /// 上传数据的方法
        /// </summary>
        private void SendData()
        {
            if (p == null)
            {
                p = new UploadBLL();
            }
            string docid = string.Empty;
            if (radioButton2.Checked)
            {
                docid = comboUpHIS.Text;
            }

            //获取网格对应的数据源，并且转换成Datatable
            DataTable dt=(DataTable)GetShowgrid().DataSource;

            if (dt.Validate())
            {
                //2015-06-01 增加判断箱码信息为空时不允许上传
                string SJLX = tabControl1.SelectedTab.Name;
                if( SJLX.RightIs("_XmEntry"))
                {
                    if (!p.CheckDataTable(dt))
                    {
                        return;
                    }
                }
                string strmsg = p.UploadData(dt.Copy(), tabControl1.SelectedTab.Name, docid);
                if (string.IsNullOrWhiteSpace(strmsg))
                {
                    MsgHelper.ShowInformationMsgBox("文件上报成功！");
                    dt.Rows.Clear(); 
                }
                else
                {
                    MsgHelper.ShowErrorMsgBox("文件上报失败:" + strmsg);
                }
            }
            else
            {
                MsgHelper.ShowInformationMsgBox("请先查询出数据再进行上传！");
            }
        }
        private void SetGrifCap(object sender)
        {
            if (p == null)
            {
                p = new UploadBLL();
            }
            string caplist = p.getGridCap(tabControl1.SelectedTab.Name );
            string[] arr = caplist.Split('/');
            DataGridView Mygrid = (DataGridView)sender;
            for (int i = 0; i < arr.Length; i++)
            {
                Mygrid.Columns[i].HeaderCell.Value = arr[i]; 
            }
        }
        //设置某些列可以编辑
        private void SetGridEnEdit(object sender)
        {
            DataGridView Mygrid = (DataGridView)sender;
            string gridname=Mygrid.Name.Replace("GV","");
            if (Common.Right(gridname, "_XmEntry".Length).Equals("_XmEntry")){
                for (int i=0 ;i<Mygrid.Columns.Count-1;i++)
                {
                    if (Mygrid.Columns[i].Name.Equals("XM"))
                    {
                        Mygrid.Columns[i].ReadOnly = false;
                    }
                    else if (Mygrid.Columns[i].Name.Equals("ZSM"))
                    { Mygrid.Columns[i].ReadOnly = false; }
                    else
                    {
                        Mygrid.Columns[i].ReadOnly = true;
                    }
                }
            }
            else if (gridname.Equals("scqyCpjysmEntry"))
            {
                
               
                for (int i = 0; i < Mygrid.Columns.Count - 1; i++)
                {
                    //if (Mygrid.Columns[i].Name.Equals("FILE_CONTENT"))
                    //{
                    //    Mygrid.Columns[i].ReadOnly = false;
                    //}
                    //else
                    //{
                        Mygrid.Columns[i].ReadOnly = true;
                    //}
                }

                Mygrid.Columns["FILE_CONTENT"].ReadOnly = false;
                Mygrid.Columns["FILE_CONTENT"].Width = 200;
            }
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            comboUpHIS.Enabled = radioButton2.Checked;
            //查看结果的按钮可用，但是是序号，这里有点不太妥
            toolbar.Items[2].Enabled = radioButton2.Checked;
            FreshComboxHis();

            DataTable dt = (DataTable)GetShowgrid().DataSource;
            if (dt.Validate())
            {
               dt.Rows.Clear();
            }
        }

        private void FreshComboxHis()
        {
            try
            {
                if (p == null)
                {
                    p = new UploadBLL();
                }
                DataTable dt = p.GetSendHIS(tabControl1.SelectedTab.Name, new UploadArgs());
                this.comboUpHIS.DataSource = dt;//也可以用ds，此处就是ds.Tables[0];

                this.comboUpHIS.DisplayMember = "DOCUMENTID"; //绑定显示成员的名字
                this.comboUpHIS.ValueMember = "DOCUMENTID";//绑定combox显示成员的值
                if (comboUpHIS.Items.Count > 0)
                {
                    this.comboUpHIS.SelectedIndex = 0;
                }
            }
            catch { }
        }
        private DataGridView GetShowgrid()
        {
            DataGridView dg=null ;
            if (tabControl1.SelectedTab.Controls.Find("GV" + tabControl1.SelectedTab.Name, true).Length > 0)
            {
                dg =(DataGridView)tabControl1.SelectedTab.Controls.Find("GV" + tabControl1.SelectedTab.Name, true)[0];
            }
            return dg;
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            FreshComboxHis();
        }

        private void DateSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            DateTime bdt=DateTime.Today;
            DateTime edt = DateTime.Today;
            switch (DateSelect.Text)
            {
                case "今天":
                    bdt = DateTime.Today;
                    edt = DateTime.Today;
                    break;
                case "昨天":
                    bdt = DateTime.Today.AddDays(-1);
                    edt = DateTime.Today.AddDays(-1);
                    break;
                case "上旬":
                    bdt = DateTime.Parse(DateTime.Today.Year.ToString() + "-" + DateTime.Today.Month.ToString() + "-01");
                    edt = DateTime.Parse(DateTime.Today.Year.ToString() + "-" + DateTime.Today.Month.ToString() + "-11");
                    break;
                case "中旬":
                    bdt = DateTime.Parse(DateTime.Today.Year.ToString() + "-" + DateTime.Today.Month.ToString() + "-11");
                    edt = DateTime.Parse(DateTime.Today.Year.ToString() + "-" + DateTime.Today.Month.ToString() + "-20");
                    break;
                case "下旬":
                    bdt = DateTime.Parse(DateTime.Today.Year.ToString() + "-" + DateTime.Today.Month.ToString() + "-20");
                    edt = DateTime.Parse(DateTime.Today.Year.ToString() + "-" + (DateTime.Today.Month + 1) + "-01");
                    break;
                case "本月":
                    bdt = DateTime.Parse(DateTime.Today.Year.ToString() + "-" + DateTime.Today.Month.ToString() + "-01");
                    edt = DateTime.Today;
                    break;
                case "上月":
                    bdt = DateTime.Parse(DateTime.Today.Year.ToString() + "-" + (DateTime.Today.Month - 1) + "-01");
                    edt = DateTime.Parse(DateTime.Today.Year.ToString() + "-" + (DateTime.Today.Month) + "-01").AddDays(-1);
                    break;
                case "本年":
                    bdt = DateTime.Parse(DateTime.Today.Year.ToString() + "-01-01");
                    edt = DateTime.Today;
                    break;
            }

            dtBegin.Value = bdt;
            dtEnd.Value = edt;
        }

        private void FrmUpload_Load(object sender, EventArgs e)
        {
            pictureBox1.Visible = (CurrentUser.Instance.SoftType.Equals("练习版"));
            toolbar.Items[2].Enabled = radioButton2.Checked;
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void FrmUpload_FormClosed(object sender, FormClosedEventArgs e)
        {
        }

        private void LookResult()
        {
            //获取上传生成的ID，从comboUp这个 combox控件中取
            string docid = comboUpHIS.Text;
            if (!string.IsNullOrWhiteSpace(docid))
            {
                if (p == null)
                {
                    p = new UploadBLL();
                }
                string  strmsg= p.LookResult(docid);
                MsgHelper.ShowInformationMsgBox(strmsg); 
            }
            else
            {
                MsgHelper.ShowInformationMsgBox("请选择已经上传的ID进行查询！");
            }
        }
    }
}
